package db

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

const (
	wdSQLUser   = "wd"
	wdSQLPasswd = "123"
	wdSQLHost   = "127.0.0.1"
	wdSQLPost   = "3306"
)

//DB  数据库连接实体
var DB *sqlx.DB
var err error
var Stmt = make(map[string]*sql.Stmt)
var stmthand = make(map[string]string)

const (
	InsertProduct  = "InsertProduct"
	SelectProduct  = "SelectProduct"
	DeleteProduct  = "DeleteProduct"
	UpdateProduct  = "UpdateProduct"
	SelectProducts = "SelectProducts"
)

func addSQLStmtStr() {
	stmthand[InsertProduct] = "insert into product(productName,productNum,productImage,productUrl) values(?,?,?,?)"
	stmthand[SelectProduct] = "select productName,productNum,productImage,productUrl from product where ID = ? limit 1"
	stmthand[DeleteProduct] = "delete from product where ID = ? limit 1"
	stmthand[UpdateProduct] = "update product set productName=?,productNum=?,productImage=?,productUrl=? where ID = ? limit 1"
	stmthand[SelectProducts] = "select * from product where ID > ? order by ID desc limit ?"
}

//StmtInit ..预处理sql语句
func StmtInit() {
	addSQLStmtStr()
	for k, v := range stmthand {
		Stmt[k], err = DB.Prepare(v)
		if err != nil {
			log.Fatalf(err.Error())
		}
	}
}
func init() {
	dns := fmt.Sprintf("%s:%s@tcp(%s:%s)/iris", wdSQLUser, wdSQLPasswd, wdSQLHost, wdSQLPost)
	DB, err = sqlx.Open("mysql", dns)
	if err != nil {
		log.Fatalln(err.Error())
	}
	if err = DB.Ping(); err != nil {
		log.Fatalln(err.Error())
	}
	DB.SetMaxOpenConns(1024)
	DB.SetMaxIdleConns(128)
	StmtInit()
	log.Printf("mysql DB init success")
}
